package com.yundin.utils;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.storage.Configuration;
import com.qiniu.http.Response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 七牛云工具类
 */
@Data
@AllArgsConstructor
@Slf4j
public class QiniuOssUtil {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    //上传文件
    public String  upload2Qiniu(byte[] bytes, String fileName){
//构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKeyId, accessKeySecret);
        String upToken = auth.uploadToken(bucketName);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
//解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("http://");
        stringBuilder.append(endpoint).append("/").append(fileName);
        log.info("文件上传到:{}", stringBuilder.toString());
        System.out.println(stringBuilder.toString());
        return stringBuilder.toString();

    }
    //删除文件
    public  void deleteFileFromQiniu(String fileName){
//构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        String key = fileName;
        Auth auth = Auth.create(accessKeyId, accessKeySecret);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucketName, key);
        } catch (Exception ex) {
//如果遇到异常，说明删除失败
            System.err.println(ex.getMessage());
        }
    }
}
